﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace MotivLogger
{
    public class SynchQueue<T>
    {
        readonly int _Capacity = 0;
        readonly Queue<T> _Queue = new Queue<T>();
        readonly object _Key = new object();
        bool _Quit = false;

        public SynchQueue( int capacity = 3)
        {
            _Capacity = capacity;
        }

        public void Quit()
        {
            lock ( _Key )
            {
                _Quit = true;

                Monitor.PulseAll( _Key );
            }
        }

        public bool Enqueue( T t )
        {
            lock ( _Key )
            {
                while ( !_Quit && _Queue.Count >= _Capacity ) Monitor.Wait( _Key );

                if ( _Quit ) return false;

                _Queue.Enqueue( t );

                Monitor.PulseAll( _Key );
            }
            return true;
        }

        public bool Dequeue( out T t )
        {
            t = default( T );

            lock ( _Key )
            {
                while ( !_Quit && _Queue.Count == 0 ) Monitor.Wait( _Key );

                if ( _Queue.Count == 0 ) return false;

                t = _Queue.Dequeue();

                Monitor.PulseAll( _Key );
            }

            return true;
        }
    }
}
